<template>
  <n-modal v-model:show="isOpen" preset="dialog" title="导出饮食记录">
    <template #header>
      <div class="modal-header">
        <h3>导出饮食记录</h3>
      </div>
    </template>

    <div class="export-dialog-content">
      <div class="export-options">
        <!-- 导出类型选择 -->
        <div class="option-section">
          <h3>导出类型</h3>
          <n-radio-group v-model:value="exportType">
            <n-space vertical>
              <n-radio value="detail">
                <div>
                  <h4>详细记录</h4>
                  <p>包含每个食物的详细摄入信息</p>
                </div>
              </n-radio>
              <n-radio value="summary">
                <div>
                  <h4>营养汇总</h4>
                  <p>按日期汇总的营养成分数据</p>
                </div>
              </n-radio>
              <n-radio value="both">
                <div>
                  <h4>详细记录 + 营养汇总</h4>
                  <p>包含详细记录和汇总数据两个工作表</p>
                </div>
              </n-radio>
              <n-radio value="analysis">
                <div>
                  <h4>营养分析报告</h4>
                  <p>按日期统计的营养分析数据</p>
                </div>
              </n-radio>
            </n-space>
          </n-radio-group>
        </div>

        <!-- 日期范围选择 -->
        <div class="option-section">
          <h3>日期范围</h3>
          <n-checkbox v-model:checked="enableDateRange">限制日期范围</n-checkbox>

          <div v-if="enableDateRange" class="date-range-inputs">
            <n-form-item label="开始日期">
              <n-date-picker
                v-model:value="startDateValue"
                type="date"
                placeholder="选择开始日期"
              />
            </n-form-item>
            <n-form-item label="结束日期">
              <n-date-picker
                v-model:value="endDateValue"
                type="date"
                placeholder="选择结束日期"
              />
            </n-form-item>
          </div>
        </div>

        <!-- 文件名设置 -->
        <div class="option-section">
          <h3>文件设置</h3>
          <n-form-item label="文件名">
            <n-input
              v-model:value="filename"
              placeholder="请输入文件名"
              clearable
            />
          </n-form-item>
          <p class="filename-note">
            文件将自动添加 .xlsx 扩展名
          </p>
        </div>

        <!-- 预览信息 -->
        <div class="option-section" v-if="previewInfo">
          <h3>导出预览</h3>
          <n-card>
            <div class="preview-item">
              <span class="preview-label">记录数量:</span>
              <span class="preview-value">{{ previewInfo.totalRecords }} 条</span>
            </div>
            <div class="preview-item">
              <span class="preview-label">日期范围:</span>
              <span class="preview-value">{{ previewInfo.dateRange }}</span>
            </div>
            <div class="preview-item">
              <span class="preview-label">文件大小:</span>
              <span class="preview-value">约 {{ previewInfo.estimatedSize }}</span>
            </div>
          </n-card>
        </div>
      </div>
    </div>

    <template #action>
      <n-space>
        <n-button @click="$emit('close')">
          取消
        </n-button>
        <n-button
          type="primary"
          @click="handleExport"
          :disabled="!canExport || isExporting"
          :loading="isExporting"
        >
          {{ isExporting ? '导出中...' : '导出' }}
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
// 使用Naive UI组件
import type { Event } from '@/types'
import { 
  exportDietTrackingToExcel, 
  exportNutritionAnalysisToExcel 
} from '@/utils/excel-export'

interface Props {
  isOpen: boolean
  events: Event[]
}

interface Emits {
  (e: 'close'): void
  (e: 'exported', filename: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const exportType = ref<'detail' | 'summary' | 'both' | 'analysis'>('both')
const enableDateRange = ref(false)
const startDateValue = ref<number>(Date.now() - 30 * 24 * 60 * 60 * 1000)
const endDateValue = ref<number>(Date.now())
const filename = ref('')
const isExporting = ref(false)

// 计算默认文件名
const defaultFilename = computed(() => {
  const today = new Date().toISOString().split('T')[0]
  const typeMap = {
    detail: '饮食详细记录',
    summary: '营养汇总',
    both: '饮食跟踪记录',
    analysis: '营养分析报告'
  }
  return `${typeMap[exportType.value]}_${today}`
})

// 监听导出类型变化，更新默认文件名
watch([exportType, enableDateRange, startDateValue, endDateValue], () => {
  if (!filename.value) {
    filename.value = defaultFilename.value
  }
})

// 过滤后的事件
const filteredEvents = computed(() => {
  let events = props.events.filter(event => 
    event.event_type?.name === '饮食跟踪' && event.extra_data?.foods_intake
  )

  if (enableDateRange.value) {
    const start = new Date(startDateValue.value).toISOString().split('T')[0]
    const end = new Date(endDateValue.value).toISOString().split('T')[0]
    events = events.filter(event =>
      event.start_date >= start && event.start_date <= end
    )
  }

  return events
})

// 预览信息
const previewInfo = computed(() => {
  if (filteredEvents.value.length === 0) return null

  const dates = filteredEvents.value.map(e => e.start_date).sort()
  const dateRange = dates.length > 0 ? `${dates[0]} 至 ${dates[dates.length - 1]}` : '无'
  
  // 估算文件大小（粗略计算）
  const recordCount = filteredEvents.value.reduce((sum, event) => {
    return sum + (event.extra_data?.foods_intake?.length || 0)
  }, 0)
  const estimatedSize = recordCount < 100 ? '< 50KB' : 
                       recordCount < 1000 ? '< 200KB' : 
                       recordCount < 5000 ? '< 1MB' : '> 1MB'

  return {
    totalRecords: filteredEvents.value.length,
    dateRange,
    estimatedSize
  }
})

// 是否可以导出
const canExport = computed(() => {
  return filteredEvents.value.length > 0 && filename.value.trim()
})

// 处理导出
const handleExport = async () => {
  if (!canExport.value) return

  try {
    isExporting.value = true

    const exportFilename = `${filename.value.trim()}.xlsx`
    const dateRange = enableDateRange.value ? {
      start: new Date(startDateValue.value).toISOString().split('T')[0],
      end: new Date(endDateValue.value).toISOString().split('T')[0]
    } : undefined

    if (exportType.value === 'analysis') {
      // 导出营养分析报告
      exportNutritionAnalysisToExcel(filteredEvents.value, {
        filename: exportFilename,
        dateRange
      })
    } else {
      // 导出饮食跟踪记录
      const includeDetail = exportType.value === 'detail' || exportType.value === 'both'
      const includeSummary = exportType.value === 'summary' || exportType.value === 'both'

      exportDietTrackingToExcel(filteredEvents.value, {
        filename: exportFilename,
        includeDetail,
        includeSummary,
        dateRange
      })
    }

    // 显示成功消息
    // TODO: 使用适当的消息提示组件
    console.log(`导出成功: ${exportFilename}`)
    
    emit('exported', exportFilename)
    emit('close')
  } catch (error) {
    console.error('导出失败:', error)
    // TODO: 显示错误消息
  } finally {
    isExporting.value = false
  }
}

// 重置表单
const resetForm = () => {
  exportType.value = 'both'
  enableDateRange.value = false
  startDateValue.value = Date.now() - 30 * 24 * 60 * 60 * 1000
  endDateValue.value = Date.now()
  filename.value = ''
  isExporting.value = false
}

// 监听弹窗打开状态，重置表单
watch(() => props.isOpen, (isOpen) => {
  if (isOpen) {
    resetForm()
    filename.value = defaultFilename.value
  }
})
</script>

<style scoped>
.export-dialog-content {
  --padding-start: 16px;
  --padding-end: 16px;
}

.export-options {
  padding: 16px 0;
}

.option-section {
  margin-bottom: 32px;
}

.option-section h3 {
  margin: 0 0 16px 0;
  color: var(--ion-color-primary);
  font-size: 18px;
  font-weight: 600;
}

.date-range-inputs {
  margin-top: 16px;
}

.filename-note {
  margin: 8px 16px;
  font-size: 12px;
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.preview-item:last-child {
  margin-bottom: 0;
}

.preview-label {
  color: var(--ion-color-medium);
  font-size: 14px;
}

.preview-value {
  color: var(--ion-color-dark);
  font-weight: 500;
  font-size: 14px;
}

ion-radio-group ion-item {
  --padding-start: 0;
}

ion-radio-group ion-label h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
}

ion-radio-group ion-label p {
  margin: 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}
</style>
